package authorizedService

import (
	"crypto/rand"
	"encoding/hex"
	"encoding/json"
	"fmt"
	"gitee.com/yangguoliang001/go-gin-vue3/BO"
	"gitee.com/yangguoliang001/go-gin-vue3/QO"
	"gitee.com/yangguoliang001/go-gin-vue3/config"
	"gitee.com/yangguoliang001/go-gin-vue3/model"
	"gitee.com/yangguoliang001/go-gin-vue3/pkg/response"
	"gitee.com/yangguoliang001/go-gin-vue3/util/code"
	"gitee.com/yangguoliang001/go-gin-vue3/vo"
	"github.com/gin-gonic/gin"
	"github.com/pkg/errors"
	"io"
)

func (a *authorizedService) QueryAuthList(c *gin.Context, authReq QO.AuthorizedListReq) (authListRes vo.AuthorizedListVO, err error) {
	authListRes, err = a.authorizedDao.QueryAuthList(authReq)
	if err != nil {
		response.Fail(c, code.AuthorizedListError, code.Text(code.AuthorizedListError), gin.H{"realErr": err})
		return authListRes, err
	}
	return authListRes, nil
}

func (a *authorizedService) AddAuthorized(c *gin.Context, authReq QO.AddAuthorizedReq) (err error) {

	token, exist := c.Get("token")
	if !exist {
		response.Fail(c, code.AdminLoginError, code.Text(code.AdminLoginError), gin.H{"realErr": "用户未登录"})
		return errors.New("context 获取 token 失败")
	}
	userInfo := a.cache.Get(config.RedisKeyPrefixLoginUser + fmt.Sprintf("%s", token))
	var sessionUser BO.SessionUserInfo
	_ = json.Unmarshal([]byte(userInfo.Val()), &sessionUser)

	a.logger.Info("cache userInfo: " + userInfo.Val())

	buf := make([]byte, 10)
	_, _ = io.ReadFull(rand.Reader, buf)
	secret := hex.EncodeToString(buf) // 随机生成密钥

	var authUser model.AuthorizedDO
	authUser.BusinessKey = authReq.BusinessKey
	authUser.BusinessSecret = secret
	authUser.BusinessDeveloper = authReq.BusinessDeveloper
	authUser.Remark = authReq.Remark
	authUser.CreatedUser = sessionUser.Username
	authUser.IsUsed = -1
	authUser.IsDeleted = -1

	err = a.authorizedDao.AddAuthorized(authUser)
	if err != nil {
		response.Fail(c, code.AuthorizedCreateError, code.Text(code.AuthorizedCreateError), gin.H{"realErr": err})
		return err
	}

	return nil
}

func (a *authorizedService) UpdateAuthorized(c *gin.Context, authReq QO.UpdateAuthorizedReq) (err error) {
	err = a.authorizedDao.UpdateAuthorized(authReq)
	if err != nil {
		response.Fail(c, code.AuthorizedUpdateError, code.Text(code.AuthorizedUpdateError), gin.H{"realErr": err})
		return err
	}
	return nil
}

// DeleteAuthorized 删除
func (a *authorizedService) DeleteAuthorized(c *gin.Context, id int) (err error) {
	err = a.authorizedDao.DeleteAuthorized(id)
	if err != nil {
		response.Fail(c, code.AuthorizedDeleteError, code.Text(code.AuthorizedDeleteError), gin.H{"realErr": err})
		return err
	}
	return nil
}
